// api.js

import { OpenAiApi } from "./openaiApi.js";
// ... import other API providers if needed

// Main API function with streaming support
export async function callApi(
  apiUrl,
  apiKey,
  apiVersion,
  provider,
  message,
  onChunk = null,
  questionContext = null,
  requestId = null
) {
  let api;

  console.log("API调用开始, 请求ID:", requestId);
  console.log("provider:", provider, "apiUrl:", apiUrl, "apiVersion:", apiVersion, "apiKey:", apiKey ? "已设置" : "未设置");

  // 检查必要参数
  if (!apiUrl || !apiVersion) {
    const errorMsg = "API配置不完整，请在设置中配置API信息";
    console.error(errorMsg);
    throw new Error(errorMsg);
  }

  // 不论是内置提供商还是自定义提供商，统一使用OpenAI兼容接口
  api = new OpenAiApi(apiUrl, apiKey || "", apiVersion);

  // 如果提供了题目上下文，添加到对话中
  if (questionContext) {
    api.addQuestionContext(questionContext);
  }

  // 如果提供了请求ID，设置到API类
  if (requestId) {
    api.setRequestId(requestId);
  }

  try {
    const response = await api.sendRequest(message, onChunk);
    return response;
  } catch (error) {
    console.error("API调用出错:", error);
    throw error; // 将错误抛出，让调用者处理
  }
}

// Add a default export
export default {
  callApi,
};
